package com.cqtd.menu.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.cqtd.base.action.FooGenericAction;
import com.cqtd.base.pojo.FooGenericSearch;
import com.cqtd.base.pojo.FooGenericSearchResult;
import com.cqtd.menu.model.Button;
import com.cqtd.menu.model.MenuSolution;
import com.cqtd.menu.model.Module;
import com.cqtd.menu.pojo.ButtonNode;
import com.cqtd.menu.pojo.CenterMenuJson;
import com.cqtd.menu.pojo.MenuNode;
import com.cqtd.menu.pojo.ToolbarNode;
import com.cqtd.menu.pojo.TreeNode;
import com.cqtd.util.FooUtils;
import com.cqtd.util.StaticMethod;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;

@Controller
@RequestMapping("/menusolution/menuSolutionAction")
public class MenuSolutionAction extends FooGenericAction {
	
	@RequestMapping("/getMenuSolustionButton")
	public void getMenuSolustionButton(HttpServletRequest request,HttpServletResponse response) {
		/*
		//String hql = "from PersonPO p left join fetch p.addresses a";
		String hql = "select m from Module m left join fetch m.buttons b";
		
//		String hql = "select new com.cqtd.menu.pojo.MenuSolutionVO(menuId,  controlurl,  menuiconcls,"
//			 +"leaf,  mgrurl,  orderNo,  parentId,"
//			 +"text,  buttonId,  buttonName,  buttonNo,"
//			 +"iconcls,  buttonOrderNo,  status,  menuNo) from Module m left join fetch m.buttons b";
		FooGenericSearch fooGenericSearch = new FooGenericSearch();
		fooGenericSearch.setQueryHql(hql);
		FooGenericSearchResult fooGenericSearchResult = fooGenericService.search(fooGenericSearch);
		
//		List<MenuSolutionVO> myUsers = (List<MenuSolutionVO>) fooGenericSearchResult.getResult();      
//		for(MenuSolutionVO myUser : myUsers){      
//			logger.info(JSON.toJSONStringWithDateFormat(myUser,"yyyy-MM-dd HH:mm:ss"));
//		} 
		
		List myUsers = fooGenericSearchResult.getResult();      
		for(Object myUser : myUsers){      
			logger.info(JSON.toJSONStringWithDateFormat(myUser,"yyyy-MM-dd HH:mm:ss"));
		} 
		*/
		
		List<TreeNode> list = tree();
		try {
			FooUtils.printJsonObject(response, list);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@SuppressWarnings("unchecked")
	private List<TreeNode> tree() {
		String hql = "from Module where parentId='' order by orderNo";
		
		FooGenericSearch fooGenericSearch = new FooGenericSearch();
		fooGenericSearch.setQueryHql(hql);
		
		List<Module> result = Lists.newArrayList();
		result = (List<Module>) fooGenericService.search(fooGenericSearch).getResult();
		List<TreeNode> tree = new ArrayList<TreeNode>();
		for (Module t : result) {
			tree.add(this.tree(t, true));
		}
		return tree;
	}

	@SuppressWarnings("unchecked")
	private TreeNode tree(Module t, boolean recursive) {
		TreeNode node = new TreeNode();
		node.setId(t.getId());
		node.setText(t.getText());
		if (t.getIconCls() != null) {
			node.setIconCls(t.getIconCls());
		} else {
			node.setIconCls("");
		}
		String hql2 = "from Button b where b.module.id=:id order by orderNo";
		Map<String, Object> params2 = new HashMap<String, Object>();
		params2.put("id",t.getId());
		FooGenericSearch fooGenericSearch2 = new FooGenericSearch();
		fooGenericSearch2.setQueryHql(hql2);
		
		List<Button> result2 = Lists.newArrayList();
		result2= (List<Button>) fooGenericService.search(fooGenericSearch2,params2)
				.getResult();
		String s = "";
		for(Button button : result2){      
			s+=","+button.getId()+"^"+button.getText();      
	    }
		s = s.replaceFirst(",", "");
		node.setButtons(s);
		
		if("true".equalsIgnoreCase(t.getLeaf())){
			node.setExpanded("false");
			node.setLeaf("true");
		}else{
			node.setExpanded("true");
			node.setLeaf("false");
		}
		
		if ("false".equalsIgnoreCase(t.getLeaf())) {
			if (recursive) {// 递归查询子节点
				String hql = "from Module where parentId=:id order by orderNo";
				Map<String, Object> params = new HashMap<String, Object>();
				params.put("id",t.getId());
				FooGenericSearch fooGenericSearch = new FooGenericSearch();
				fooGenericSearch.setQueryHql(hql);
				List<Module> result = Lists.newArrayList();
				result = (List<Module>) fooGenericService.search(fooGenericSearch,params)
						.getResult();
				
				List<TreeNode> children = new ArrayList<TreeNode>();
				for (Module r : result) {
					TreeNode tn = tree(r, true);
					children.add(tn);
				}
				node.setChildren(children);
			}
		}
		return node;
	}
	
	@RequestMapping("/add")
	@ResponseBody
	public void add(HttpServletRequest request,HttpServletResponse response) {
		String ids = StaticMethod.nullObject2String(request.getParameter("ids"));
		String[] iduse = ids.split(",");
		List<String> menuIdList = Lists.newArrayList();
		List<String> buttonIdList = Lists.newArrayList();
		for(String id:iduse){
			if(id.contains("^")){
				buttonIdList.add(id);
			}else{
				menuIdList.add(id);
			}
		}
		logger.info(Joiner.on(",").join(menuIdList));
		logger.info(Joiner.on(",").join(buttonIdList));
		
		String menuIds = Joiner.on(",").join(menuIdList);
		List<Module> menuList = getModuleList(menuIds);
		
		//存放菜单ID，菜单的键值对，解析button时要用到
		Map<String,Module> menuIdMap = Maps.newHashMap();
		
		Set<String> parentIdSet = Sets.newHashSet();
		for (Module module : menuList) {
			parentIdSet.add(module.getParentId());
			menuIdMap.put(module.getId(), module);
		}
		
		//查出所有父亲节点的对象
		String parentMenuIds = Joiner.on(",").join(parentIdSet);
		List<Module> parentMenuList = getModuleList(parentMenuIds);
		Map<String,MenuNode> parentMenuIdMap = Maps.newHashMap();
		for (Module module : parentMenuList) {
			MenuNode menuNode = new MenuNode();
			BeanUtils.copyProperties(module, menuNode);
			parentMenuIdMap.put(module.getId(), menuNode);
		}
		
		List<MenuNode> brotherList = Lists.newArrayList();
		for (String parentId : parentIdSet) {
			List<MenuNode> singObjList = Lists.newArrayList();
			for (Module module : menuList) {
				if(parentId.equalsIgnoreCase(module.getParentId())){
					MenuNode menuNode = new MenuNode();
					BeanUtils.copyProperties(module, menuNode);
					singObjList.add(menuNode);
				}
			}
			//单个父亲节点
			MenuNode m = parentMenuIdMap.get(parentId);
			m.setChildren(singObjList);
			brotherList.add(m);
		}
		Map<String, Object> map = Maps.newHashMap();
		MenuNode menuNode = new MenuNode();
		menuNode.setChildren(brotherList);
		map.put("models",menuNode);
		logger.info(JSON.toJSONStringWithDateFormat(map,"yyyy-MM-dd HH:mm:ss"));
		
		//处理button
		Set<String> menuIdSet = Sets.newHashSet();
		List<String> buttonIdsList = Lists.newArrayList();
		for (String menu_button_id : buttonIdList) {
			String[] mbids = menu_button_id.split("\\^");
			String menuId = mbids[0];
			String buttonId = mbids[1];
			menuIdSet.add(menuId);
			buttonIdsList.add(buttonId);
		}
		//获取所有的button对象
		String buttonIds = Joiner.on(",").join(buttonIdsList);
		List<Button> buttonObjectList =  getButtonList(buttonIds);
		List<CenterMenuJson> centerMenuJsonList =  Lists.newArrayList();
		for (String menuId : menuIdSet) {
			CenterMenuJson centerMenuJson = new CenterMenuJson();
			ToolbarNode toolbar = new ToolbarNode();
			List<ToolbarNode> toolbarList = Lists.newArrayList();
			List<ButtonNode> buttons = Lists.newArrayList();
			for (Button button : buttonObjectList) {
				if(menuId.equalsIgnoreCase(button.getMenuId())){
					ButtonNode buttonNode = new ButtonNode();
					BeanUtils.copyProperties(button, buttonNode);
					buttons.add(buttonNode);
				}
			}
			toolbar.setItems(buttons);
			toolbarList.add(toolbar);
			centerMenuJson.setMenuId(menuIdMap.get(menuId).getMenuNo());
			centerMenuJson.setToolbarId(toolbarList);
			centerMenuJsonList.add(centerMenuJson);
		}
		
		Map<String, Object> buttonMap = Maps.newHashMap();
		buttonMap.put("data",centerMenuJsonList);
		logger.info(JSON.toJSONStringWithDateFormat(buttonMap,"yyyy-MM-dd HH:mm:ss"));
		
		MenuSolution menuSolution = new MenuSolution();
		String westMenuJson = JSON.toJSONStringWithDateFormat(map,"yyyy-MM-dd HH:mm:ss");
		String centerMenuJson = JSON.toJSONStringWithDateFormat(buttonMap,"yyyy-MM-dd HH:mm:ss");
		menuSolution.setCenterMenuJson(centerMenuJson);
		menuSolution.setWestMenuJson(westMenuJson);
		menuSolution.setSolutionName("cdfa");
		menuSolution.setSolutionDesc("菜单方案");
		
		fooGenericService.save(menuSolution);
		try {
			FooUtils.printJsonSuccessMsg(response);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@SuppressWarnings("unchecked")
	private List<Module> getModuleList(String ids){
		String hql = "from Module where id in ("+ids+") order by orderNo";
		FooGenericSearch fooGenericSearch = new FooGenericSearch();
		fooGenericSearch.setQueryHql(hql);
		FooGenericSearchResult myResult = fooGenericService.search(fooGenericSearch);
		List<Module> menuList = (List<Module>) myResult.getResult();
		return menuList;
	}
	@SuppressWarnings("unchecked")
	private List<Button> getButtonList(String ids){
		String hql = "from Button where id in ("+ids+") order by orderNo";
		FooGenericSearch fooGenericSearch = new FooGenericSearch();
		fooGenericSearch.setQueryHql(hql);
		FooGenericSearchResult myResult = fooGenericService.search(fooGenericSearch);
		List<Button> buttonList = (List<Button>) myResult.getResult();
		return buttonList;
	}
	
	@SuppressWarnings({ "unchecked", "unused" })
	private MenuNode westTree(MenuNode menuNode,MenuNode pMenuNode) {
		if(menuNode!=null){
			String parentId = menuNode.getParentId();
			if(!"".equalsIgnoreCase(parentId)&&parentId!=null){
				String phql = "from Module where id=:parentId order by orderNo";
				Map<String, Object> params = new HashMap<String, Object>();
				params.put("parentId",parentId);
				FooGenericSearch fooGenericSearch = new FooGenericSearch();
				fooGenericSearch.setQueryHql(phql);
				List<Module> result = Lists.newArrayList();
				result = (List<Module>) fooGenericService.search(fooGenericSearch,params)
						.getResult();
				if(result!=null&&result.size()>0){
					Module module = result.get(0);
					BeanUtils.copyProperties(module, pMenuNode);
					List<MenuNode> children = new ArrayList<MenuNode>();
					children.add(menuNode);
					pMenuNode.setChildren(children);
					return pMenuNode;
				}
			}
		}
		return null;
	}
	
	public static void main(String[] args) {
		String a = "1^3,1^4,1^2,1^1,";
		String[] iduse = a.split(",");
		List<String> s = Lists.newArrayList();
		for (String string : iduse) {
			s.add(string);
			
			String[] x = string.split("\\^");
			System.out.println(x[0]+":"+x[1]);
		}
	}
	
	
}
